package mapper

import (
	"github.com/beego/beego/v2/client/orm"
	"ksd-social-api/commons/page"
	"ksd-social-api/modules/special/model"
	"ksd-social-api/modules/special/model/context"
)

type SpecialMapper struct{}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询专题信息
 */
func (mapper *SpecialMapper) GetById(id uint64, systemId uint64) (special *model.Special, err error) {
	// 1: 创建一个数据连接
	db := orm.NewOrm()
	// 2: 赋予id给结构体
	dbSpecial := model.Special{Id: id, SystemId: systemId}
	// 3: 读取id的数据放入到结构体，进行返回
	err = db.Read(&dbSpecial, "id", "system_id")
	// 4: 结构返回
	return &dbSpecial, err
}

func (mapper *SpecialMapper) CountSpecialViewCount(specialId uint64, systemId uint64) int64 {
	// 创建orm对象
	mysql := orm.NewOrm()
	var total int64
	err := mysql.Raw("SELECT viewcount FROM xk_special WHERE id = ? and system_id = ?", specialId, systemId).QueryRow(&total)
	if nil != err {
		return -1
	}
	return total
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询专题信息
 */
func (mapper *SpecialMapper) GetByPath(path string, systemId uint64) (special *model.Special, err error) {
	// 1: 创建一个数据连接
	db := orm.NewOrm()
	// 2: 赋予id给结构体
	dbSpecial := model.Special{Path: path, SystemId: systemId}
	// 3: 读取id的数据放入到结构体，进行返回
	err = db.Read(&dbSpecial, "path", "system_id")
	// 4: 结构返回
	return &dbSpecial, err
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询专题信息，不包含内容
 */
func (mapper *SpecialMapper) GetByIdTOPay(id uint64, systemId uint64) (special *model.Special, err error) {
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	cond = cond.And("id", id).And("system_id", systemId)
	qs := mysql.QueryTable("xk_special")
	dbSpecial := model.Special{}
	err = qs.SetCond(cond).One(&dbSpecial,
		"id",
		"title",
		"img",
		"price",
		"description",
		"realprice",
	)
	// 4: 结构返回
	return &dbSpecial, err
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询专题分页
 */
func (mapper *SpecialMapper) FindSpecialListAndPage(ctx context.SpecialSearchContext) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	specialList := []model.Special{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_special")
	// 4: 设定两个条件
	cond = cond.And("status", 1).
		And("is_deleted", 0).
		And("system_id", ctx.SystemId)
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	if ctx.CategoryCid > 0 {
		cond = cond.And("category_id", ctx.CategoryCid)
	}
	if ctx.PayFlag > 0 {
		cond = cond.And("pay_flag", ctx.PayFlag)
	}
	if ctx.PushFlag > 0 {
		cond = cond.And("push_flag", ctx.PushFlag)
	}
	if ctx.HotFlag > 0 {
		cond = cond.And("hot_flag", ctx.HotFlag)
	}
	if ctx.NewFlag > 0 {
		cond = cond.And("new_flag", ctx.NewFlag)
	}
	if ctx.Specialtype > 0 {
		cond = cond.And("specialtype", ctx.Specialtype)
	}
	// 如果用户输入的搜索关键词
	if len(ctx.Keyword) > 0 {
		cond1 := orm.NewCondition()
		cond1 = cond1.And("title__icontains", ctx.Keyword).Or("nickname__icontains", ctx.Keyword)
		cond = cond.AndCond(cond1)
	}

	// 6：执行count查询
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(ctx.PageNo, ctx.PageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	querySeter := qs.SetCond(cond)
	if ctx.OrderNum == 0 {
		querySeter = querySeter.OrderBy("-create_time")
	} else if ctx.OrderNum == 1 {
		querySeter = querySeter.OrderBy("-viewcount")
	} else if ctx.OrderNum == 2 {
		querySeter = querySeter.OrderBy("-update_time")
	} else if ctx.OrderNum == 3 { // 最后更新
		querySeter = querySeter.OrderBy("sorted")
	}
	_, err2 := querySeter.Limit(page.PageSize, page.CurrentPage).All(&specialList,
		"id",
		"title",
		"tags",
		"pan_pwd",
		"try_link",
		"specialtype",
		"description",
		"viewcount",
		"create_time",
		"update_time",
		"comment_flag",
		"is_deleted",
		"avatar",
		"nickname",
		"status",
		"userid",
		"img",
		"fav_num",
		"comment_num",
		"price",
		"realprice",
		"new_flag",
		"hot_flag",
		"push_flag",
		"category_id",
		"category_name",
		"uuid",
		"like_num",
		"path",
		"stimer",
		"pay_flag",
		"buy_num")
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}

/**
 * @desc 更新浏览数
 * @author feige
 * @date 2023-11-14
 * @version 1.0
 */
func (mapper *SpecialMapper) UpdateViewCount(id uint64, systemId uint64) bool {
	newOrm := orm.NewOrm()
	_, err := newOrm.Raw("update  xk_special set viewcount = viewcount +1  where id = ? and system_id = ?", id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @desc 更新浏览数
 * @author feige
 * @date 2023-11-14
 * @version 1.0
 */
func (mapper *SpecialMapper) UpdateFavNum(id uint64, systemId uint64, num int) bool {
	newOrm := orm.NewOrm()
	_, err := newOrm.Raw("update  xk_special set fav_num = fav_num + ?  where id = ? and system_id = ?", num, systemId, id).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @desc 更新浏览数
 * @author feige
 * @date 2023-11-14
 * @version 1.0
 */
func (mapper *SpecialMapper) UpdateLikeNum(id uint64, systemId uint64, num int) bool {
	newOrm := orm.NewOrm()
	_, err := newOrm.Raw("update  xk_special set like_num = like_num + ?  where id = ? and system_id = ?", num, id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 我学习的专题
 */
func (mapper *SpecialMapper) FindMySpecialsPage(userId uint64, systemId uint64, pageNo int64, pageSize int64) (p *page.Page, err error) {
	// 准备容器对象，开始装载数据库数据
	specialList := []model.Special{}
	//创建orm对象
	mysql := orm.NewOrm()

	var total int64 = 0
	// 开始执行sql查询
	err = mysql.Raw(`select count(1) from xk_special_user_buy t2,xk_special t1 where t1.id = t2.opid and t1.status = 1 and t1.is_deleted = 0 and t2.user_id = ? and t2.system_id = ?`, userId, systemId).QueryRow(&total)
	if err != nil {
		return nil, err
	}
	// 重新换算分页和规则
	page := p.Page(pageNo, pageSize, total)
	// 执行count查询
	// 开始执行sql查询
	_, err2 := mysql.Raw(`
		select 
		t1.id,
		t1.title,
		t1.tags,
		t1.mode,
		t1.net_link,
		t1.pan_link,
		t1.pan_pwd,
		t1.try_link,
		t1.description,
		t1.viewcount,
		t1.download_nums,
		t1.create_time,
		t1.update_time,
		t1.comment_flag,
		t1.is_deleted,
		t1.avatar,
		t1.nickname,
		t1.status,
		t1.userid,
		t1.img,
		t1.fav_num,
		t1.comment_num,
		t1.price,
		t1.realprice,
		t1.new_flag,
		t1.hot_flag,
		t1.push_flag,
		t1.category_id,
		t1.category_name,
		t1.specialtype,
		t1.uuid,
		t1.like_num,
		t1.vip_flag,
		t1.buy_num,
		t1.stimer,
		t1.path,
		t1.pay_flag
		from xk_special_user_buy t2,xk_special t1 where t1.id = t2.opid and t1.status = 1 and t1.is_deleted = 0 and t2.user_id = ? order by t2.create_time desc limit ?,?`,
		userId, page.CurrentPage, page.PageSize).QueryRows(&specialList)

	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil, err2
	}
	return page, nil
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 我浏览过的专题
 */
func (mapper *SpecialMapper) FindMySpecialsBroswerPage(userId uint64, systemId uint64, pageNo int64, pageSize int64) (p *page.Page, err error) {
	// 准备容器对象，开始装载数据库数据
	specialList := []model.Special{}
	//创建orm对象
	mysql := orm.NewOrm()

	var total int64 = 0
	// 开始执行sql查询
	err = mysql.Raw(`select count(1) from xk_special_user_hits t2,xk_special t1 where t1.id = t2.opid and t1.status = 1 and t1.is_deleted = 0 and t2.user_id = ? and t2.system_id = ?`, userId, systemId).QueryRow(&total)
	if err != nil {
		return nil, err
	}
	// 重新换算分页和规则
	page := p.Page(pageNo, pageSize, total)
	// 执行count查询
	// 开始执行sql查询
	_, err2 := mysql.Raw(`
		select 
		t1.id,
		t1.title,
		t1.tags,
		t1.mode,
		t1.net_link,
		t1.pan_link,
		t1.pan_pwd,
		t1.try_link,
		t1.description,
		t1.viewcount,
		t1.download_nums,
		t1.create_time,
		t1.update_time,
		t1.comment_flag,
		t1.is_deleted,
		t1.avatar,
		t1.nickname,
		t1.status,
		t1.userid,
		t1.img,
		t1.fav_num,
		t1.comment_num,
		t1.price,
		t1.realprice,
		t1.new_flag,
		t1.hot_flag,
		t1.push_flag,
		t1.category_id,
		t1.category_name,
		t1.specialtype,
		t1.uuid,
		t1.like_num,
		t1.vip_flag,
		t1.buy_num,
		t1.stimer,
		t1.path,
		t1.pay_flag
		from xk_special_user_hits t2,xk_special t1 
		where t1.id = t2.opid and t1.status = 1 and t1.is_deleted = 0 and t2.user_id = ? 
		order by t2.create_time desc limit ?,?`,
		userId, page.CurrentPage, page.PageSize).QueryRows(&specialList)

	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil, err2
	}
	return page, nil
}

/**
 * @desc 保存用户的专题浏览记录
 * @author feige
 * @date 2023-11-14
 * @version 1.0
 */
func (mapper *SpecialMapper) SaveUserSpecialHits(specialUserHits *model.SpecialUserHits) bool {
	newOrm := orm.NewOrm()
	var specialcount int
	err := newOrm.Raw("select count(1) from xk_special_user_hits where opid = ?  and user_id = ? and system_id = ?").
		SetArgs(specialUserHits.Opid, specialUserHits.UserId, specialUserHits.SystemId).QueryRow(&specialcount)
	if err == nil {
		if specialcount == 0 {
			orm.NewOrm().Insert(specialUserHits)
			return true
		} else {
			orm.NewOrm().Raw("update xk_special_user_hits set update_time = now() where opid = ?  and user_id = ? and system_id = ?").
				SetArgs(specialUserHits.Opid, specialUserHits.UserId, specialUserHits.SystemId).Exec()
			return true
		}
	}
	return false
}

/**
 * 删除专题记录
 * @author feige
 * @date 2024-01-13
 * @version 1.0
 * @desc
 */
func (mapper *SpecialMapper) RemoveSpecialHits(userId uint64, specialId uint64, systemId uint64) bool {
	_, err := orm.NewOrm().Raw("delete from xk_special_user_hits where  user_id = ? AND special_id= ? and system_id = ?", userId, specialId, systemId).Exec()
	return err == nil
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询专题分页
 */
func (mapper *SpecialMapper) FindPushSpecialListAndPage(pageNo int64, pageSize int64, categoryId uint64, systemId uint64) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	specialList := []model.Special{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_special")
	// 4: 设定两个条件
	cond = cond.And("status", 1).
		And("is_deleted", 0).
		And("push_flag", 1).
		And("system_id", systemId)
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	if categoryId > 0 {
		cond = cond.And("category_id", categoryId)
	}

	// 6：执行count查询
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(pageNo, pageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	_, err2 := qs.SetCond(cond).OrderBy("-create_time").Limit(page.PageSize, page.CurrentPage).All(&specialList,
		"id",
		"title",
		"tags",
		"try_link",
		"specialtype",
		"description",
		"viewcount",
		"create_time",
		"update_time",
		"comment_flag",
		"is_deleted",
		"avatar",
		"nickname",
		"status",
		"userid",
		"uuid",
		"img",
		"fav_num",
		"comment_num",
		"price",
		"realprice",
		"new_flag",
		"hot_flag",
		"push_flag",
		"category_id",
		"category_name",
		"uuid",
		"like_num",
		"pay_flag",
		"path",
		"stimer",
		"buy_num")
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}
